/**
 * AutoResizeTable.java
 * @author: liuex
 * 2008-1-16 ����12:43:05
 *
 * note: 
 */
package org.lex.swing.widgets;

import java.awt.Container;
import java.awt.Font;
import java.awt.FontMetrics;

import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.ListSelectionModel;
import javax.swing.event.TableModelEvent;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;

public class AutoResizeTable extends JTable {
	private int extraColumnWidth = 11;

	public AutoResizeTable() {
	}

	public AutoResizeTable(int numRows, int numColumns) {
		super(numRows, numColumns);
	}

	public AutoResizeTable(Object[][] rowData, Object[] columnNames) {
		super(rowData, columnNames);
	}

	public AutoResizeTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm) {
		super(dm, cm, sm);
	}

	public AutoResizeTable(TableModel dm, TableColumnModel cm) {
		super(dm, cm);
	}

	public AutoResizeTable(TableModel dm) {
		super(dm);
	}

	public void tableChanged(TableModelEvent e) {
		super.tableChanged(e);
		this.resizeTableColumns();
	}

	private void resizeTableColumns() {
		TableModel tm = this.getModel();
		if (null == tm)
			return;
		TableColumnModel tcm = this.getColumnModel();
		if (null == tcm)
			return;
		Font font = this.getFont();
		if (null == font)
			return;
		FontMetrics fm = this.getFontMetrics(font);
		int width = 0;
		int totalWidth = 0;
		int columnCount = tm.getColumnCount();
		if (0 == columnCount)
			return;
		for (int column = 0; column < columnCount; column++) {
			width = this.getMaxColumnWidth(tm, column, fm);
			tcm.getColumn(column).setPreferredWidth(width);
			totalWidth += width;
		}
		Container p = this.getParent();
		if (p instanceof JViewport) {
			int aWidth = p.getWidth();
			// fill width
			if (totalWidth < aWidth) {
				width += aWidth - totalWidth;
				tcm.getColumn(columnCount - 1).setPreferredWidth(width);
			}
		}
	}

	private int getMaxColumnWidth(TableModel model, int column, FontMetrics fm) {
		int rowCount = model.getRowCount();
		int maxWidth = fm.stringWidth(model.getColumnName(column));
		String str = null;
		int width = 0;
		for (int row = 0; row < rowCount; row++) {
			str = String.valueOf(model.getValueAt(row, column));
			width = fm.stringWidth(str);
			if (maxWidth < width)
				maxWidth = width;
		}
		return maxWidth + this.extraColumnWidth;
	}
}
